# -*- coding: utf-8 -*-
'''
     @Author : LiWenqian
     @File : load_asyncio.py
     @Project: scpythonProject
     @CreateTime : 2022/8/11 23:22:26
'''

import asyncio, requests, aiohttp, re, time

def acquire_img(url):
    response = requests.get(url)
    response.encoding = 'utf-8'
    content = response.text
    # 获取图片名称
    img_lst = re.findall(r"(?<=<img src=).*(?= width)", content)
    return img_lst

async def load_img(url, img_url, session):
    # 获取图片
    async with session.get(url+img_url, verify_ssl=False) as res:
        img_content = await res.content.read()
        # 保存图片
        filename = f'./img/{img_url}'
        with open(filename, 'wb+') as fp:
                fp.write(img_content)

async def main():
    url = "https://www.sanchuangedu.cn/"
    img_lst = acquire_img(url)
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.ensure_future(load_img(url, img_url, session)) for img_url in img_lst]
        await asyncio.wait(tasks)

if __name__ == "__main__":
    t1 = time.time()
    asyncio.run(main())
    t2 = time.time()
    print("下载图片共消耗时间：",t2-t1)
